package bb.lanxing.mvp.model;

import static bb.lanxing.common.config.Constants.LUSHU_BAIDU_FILE_SUFFIX;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.alibaba.fastjson.JSON;
import com.baidu.mapapi.model.LatLng;
import com.garmin.fit.MonitoringReader;

import bb.lanxing.common.config.Constants;
import bb.lanxing.lib.kt.model.geo.IGeoPoint;
import bb.lanxing.model.database.RouteBook;
import bb.lanxing.model.lushu.RouteBookCacheStrategy;
import bb.lanxing.model.lushu.WayPoint;
import bb.lanxing.model.map.GeoPoint;
import bb.lanxing.mvp.model.i.RouteBookSourceModel;
import bb.lanxing.nav.BaiduNavConvert;
import bb.lanxing.network.BaiduHttpClient;
import bb.lanxing.util.AppFileUtils;
import bb.lanxing.util.CommonUtil;
import bb.lanxing.util.JsonUtil;
import okhttp3.Response;

public class BaiduRouteBookSourceModelImpl extends AbstractRouteBookSourceModel implements RouteBookSourceModel {
	public BaiduRouteBookSourceModelImpl(int sourceType) {
		super(sourceType);
	}

	@Override protected boolean isSuccessful(String body) {
		try {
			return new JSONObject(body).getInt("status") == 0;
		} catch (JSONException unused) {
			return false;
		}
	}

	@Override protected RouteBook afterBuild(RouteBook routeBook, List<String> response) {
		try {
			JSONObject jSONObject = new JSONObject();
			jSONObject.put("version", Constants.LUSHU_FILE_VERSION);
			jSONObject.put("status", "OK");
			jSONObject.put("geocoded_waypoints", new JSONObject());
			JSONArray jSONArray = new JSONArray();
			JSONArray jSONArray2 = new JSONArray();
			for (String str : response) {
				jSONArray.put(new JSONObject(str).getJSONObject("result"));
			}
			JSONObject mergeServerRoutes = BaiduNavConvert.mergeServerRoutes(jSONArray);
			JSONObject jSONObject2 = new JSONObject();
			jSONObject2.put("result", mergeServerRoutes);
			jSONArray2.put(new JSONObject(JSON.toJSONString(BaiduNavConvert.parseRoute(jSONObject2))));
			jSONObject.put("routes", jSONArray2);
			// TODO: 2024/10/25 temp comment it for routes_baidu
			// jSONObject.put("routes_baidu", jSONArray);
			String jSONStr = jSONObject.toString();
			String buildExternalDirectoryPath = AppFileUtils.buildExternalDirectoryPath(Constants.LUSHU_DIRECTION_UPLOAD);
			String filePath = buildExternalDirectoryPath + (routeBook.getUuid() + LUSHU_BAIDU_FILE_SUFFIX);
			// File file = new File(buildExternalDirectoryPath, lushu.getUuid() + ".bb");
			// if (file.exists()) {
			// file.delete();
			// }
			if (AppFileUtils.writeFileWithCallBack(jSONStr, filePath)) {
				return routeBook;
			}
			return null;
		} catch (JSONException unused) {
			return routeBook;
		}
	}

	@Override protected String requestRouteBook(List<WayPoint> wayPoints) throws IOException {
		String keyOf = keyOf(wayPoints);
		RouteBookCacheStrategy cacheStrategy = getCacheStrategy();
		String str = cacheStrategy.get(keyOf);
		if (str == null) {
			Response execute = BaiduHttpClient.buildDirectionByGeoPoints(new ArrayList<>(wayPoints)).execute();
			if (execute.isSuccessful()) {
				str = execute.body().string();
				if (isSuccessful(str)) {
					cacheStrategy.put(keyOf, str);
				} else if (str.contains("2002")) {
					throw new IOException(str);
				} else {
					throw new IOException("Incorrect data");
				}
			}
		}
		return str;
	}

	@Override protected List<IGeoPoint> extractPoints(String responseBody) {
		ArrayList<IGeoPoint> arrayList = new ArrayList<>();
		try {
			JSONObject jSONObject = new JSONObject(responseBody);
			JSONArray jSONArray = jSONObject.getInt("status") == 0 ? jSONObject.getJSONObject("result").getJSONArray("routes") : null;
			if (jSONArray != null && jSONArray.length() >= 1) {
				JSONObject jSONObject2 = jSONArray.getJSONObject(0);
				ArrayList<LatLng> arrayList2 = new ArrayList<>();
				plusDistance(JsonUtil.getDoubleValue(MonitoringReader.DISTANCE_STRING, jSONObject2));
				JSONArray arrayValue = JsonUtil.getArrayValue("steps", jSONObject2);
				if (arrayValue != null) {
					for (int i = 0; i < arrayValue.length(); i++) {
						JSONObject jSONObject3 = arrayValue.getJSONObject(i).getJSONObject("stepOriginLocation");
						LatLng latLng = new LatLng(Double.parseDouble(jSONObject3.getString("lat")), Double.parseDouble(jSONObject3.getString("lng")));
						JSONObject jSONObject4 = arrayValue.getJSONObject(i).getJSONObject("stepDestinationLocation");
						LatLng latLng2 = new LatLng(Double.parseDouble(jSONObject4.getString("lat")), Double.parseDouble(jSONObject4.getString("lng")));
						List<LatLng> parseBaiduPoints = CommonUtil.parseBaiduPoints(arrayValue.getJSONObject(i).getString("path"));
						arrayList2.add(latLng);
						arrayList2.addAll(parseBaiduPoints);
						arrayList2.add(latLng2);
					}
				}
				for (LatLng latLng3 : arrayList2) {
					arrayList.add(GeoPoint.fromBaidu(latLng3.latitude, latLng3.longitude));
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return arrayList;
	}
}
